package jupitermouse.site.wordcount;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

import java.util.stream.Stream;

public class BatchWCJavaApp {

    public static void main(String[] args) throws Exception {

        String inputPath = "file:///E:\\workroom\\learn\\flink\\demo_flink\\doc\\word.txt";

        //set env
        final ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();

        //read data
        DataSource<String> dataSource = env.readTextFile(inputPath);

        //transform
        dataSource.flatMap(new FlatMapFunction<String, Tuple2<String,Integer>>() {
            @Override
            public void flatMap(String s, Collector<Tuple2<String, Integer>> collector) throws Exception {
                String[] tokens = s.toLowerCase().split(" ");
                Stream.of(tokens)
                        .forEach(item -> {
                            collector.collect(new Tuple2<>(item, 1));
                        });
            }
        }).groupBy(0).sum(1).print();

        env.execute("BatchWCJavaApp");

    }
}
